/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input, Message } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import { FieldsGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const AddManagers = ({ modal, userInfo, onCancel, onSubmit }) => {
  const { userStore: store } = useStore();
  const [currentNext, setCurrentNext] = useState(false);
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [user] = useState(() => observable({}));
  const isEdit = modal[0] === 'edit';
  useEffect(() => { if (modal.close?.startsWith?.('toClose')) handleCancel(); }, [modal]);


  useEffect(() => {
    (async () => {
      if (JSON.stringify(userInfo) !== '{}') {
        const data = userInfo;
        editCtx.origin = _.cloneDeep(data);
        _.assign(user, data);
        _.set(user, 'iphone', data.mobile);
        if (modal[0] === 'edit') setCurrentNext(true);
      }
    })();
  }, []);

  const overrideModel = {
    iphone: {
      label: t`手机号`,
      ui: {
        renderer: (v) => (
          <Input
            autoComplete="off"
            placeholder="请输入手机号"
            value={v}
            addonAfter={!isEdit && <Button type="primary" onClick={() => current(v)}>{t`下一步`}</Button>}
          />
        ),
        itemProps: { required: true },
      },
    },
  };

  const current = async (r) => {
    try {
      if (r.length !== 11) {
        return Message.warning({ content: t`请输入有效手机号` });
      }
      const res = await store.getUserProp({ propName: 'mobile', propValue: r });
      if (res) {
        Message.success(t`该用户为后台用户`);
        const info = await store.getUserMobile(r);
        setCurrentNext(true);
        _.assign(user, info);
      } else {
        Message.warning(t`当前用户非平台用户，请先添加为后台用户`);
        _.assign(user, {});
      }
    } catch (error) {
      console.log('🚀 _ file: AddManagers.jsx:79 _ error:', error);
    }
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(user, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  /**
   * @description 提交表单实现修改车辆
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    _.set(user, 'mobile', user.iphone);
    onSubmit?.(user);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      colon
      isPreview={isViewMode}
      {...formProps}
      value={user}
      onChange={handleChange}
      useLabelForErrorMessage
      autocomplete="new-password"
    >
      <FieldsGrid
        formData={user}
        mode={modal[0]}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        columns={1}
        overrideModel={overrideModel}
        fields={['iphone'].concat(currentNext ? ['fullname', 'accountId', 'password', 'email'] : [])}
      />
      <FromItem style={{ marginTop: 100, marginLeft: 100 }}>
        {currentNext && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
        <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
      </FromItem>
    </Form>
  );
};

export default observer(AddManagers);
